---
--- 灰度处理 ip规则具体实现
--- Created by E.T.
--- DateTime: 2018/11/12 17:41
---
local http_tools = require "kong.plugins.gray.tools.http_tools"
local config = require "kong.plugins.gray.tools.config"
local string_tools = require "kong.plugins.gray.tools.string_tools"
local service = kong.service
local request = kong.request
local log = kong.log
local _M = {}
--获取客户端ip
function get_client_ip()
    local headers=ngx.req.get_headers()
    local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"
    return ip
end

--跳转至上游服务
local function set_upstream(upstream_name)
    local ok, err = service.set_upstream(upstream_name)
    if not ok then
        log.err("跳转至上游服务出错：", err)
        http_tools.response(403, "没有找到[".. upstream_name .."]上游服务")
    end
end

local function do_ip(conf)
    local remote_addr = ngx.var.remote_addr
    local host = request.get_host()
    local path = request.get_path()
    local host_name = string_tools.split(host, ".")
    log.notice("请求ip->",remote_addr)
    log.notice("请求host->",host)
    log.notice("请求路径->",path)
    if conf.zuul_upstream_name == nil then
        http_tools.response(403, "需要配置zuul上游服务名称")
    end
    for i, ip in pairs(conf.outer_net_ip) do
        if remote_addr == ip then
            log.notice("跳转至上游服务->",conf.zuul_upstream_name)
            service.request.set_header("host_env", host_name[1])
            service.request.set_path(config.gateway_context_path..path)
            set_upstream(conf.zuul_upstream_name)
            break
        end
    end
end

function _M.execute(conf)
    local ok, err = do_ip(conf)
end

return _M